package com.zf.zfed.audit.base.fragment

import android.app.Application
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.zf.zfed.audit.base.BaseActivity
import com.zf.zfed.audit.base.BaseFragment

/**
 * @Author: wqq
 * @Date: 2023/3/6 10:07
 * @Description: 碎片Fragment的基础公共类，主要是初始化控件、数据、监听事件等，
 * 便于后类的继承，业务代码的规整
 */
abstract class BaseCommonFragment : BaseFragment() {
    /**
     * Activity 对象
     */
    private var activity: BaseActivity? = null

    /**
     * 初始化控件
     */
    protected open fun initViews() {}

    /**
     * 初始化数据
     */
    protected open fun initDatum() {}

    /**
     * 初始化监听器
     */
    protected open fun initListeners() {}

    override fun onAttach(context: Context) {
        super.onAttach(context)
        // 获得全局的 Activity
        activity = requireActivity() as? BaseActivity
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return getLayoutView(inflater, container, savedInstanceState)
    }

    /**
     * 获取view
     */
    protected abstract fun getLayoutView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View?

    /**
     * 加载初始化，在onCreateView方法后面调用
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        initDatum()
        initListeners()
    }

    override fun onDetach() {
        super.onDetach()
        activity = null
    }

    /**
     * 获取绑定的 Activity，防止出现 getActivity 为空
     */
    open fun getAttachActivity(): BaseActivity? {
        return activity
    }

    /**
     * 获取 Application 对象
     */
    open fun getApplication(): Application? {
        activity?.let { return it.application }
        return null
    }

}